package com.baixiaowen.xiaoaointerview.并发提升篇.LinkedBlockingDeque和SynchronousQueue工作原理一样吗;

import java.util.concurrent.*;

public class BlockingQueueTest {

    public static void main(String[] args) {
        BlockingQueue<Integer> queue;
//        queue = new ArrayBlockingQueue<>(10);
//        queue = new LinkedBlockingQueue<>(10);
//        queue = new LinkedBlockingDeque<>();
//        queue = new PriorityBlockingQueue<>();
//        queue = new LinkedTransferQueue<>();
        queue = new SynchronousQueue<>();
//        queue = new DelayQueue<>();

        // Producer
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                // 非阻塞
//                queue.offer((int)(Math.random() * 1000));
                // 阻塞
                try {
                    queue.put((int)(Math.random() * 1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }

        // Consumer
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                while (true) {
                    // 非阻塞
//                    Integer x = queue.poll();
                    // 阻塞
                    Integer x = null;
                    try {
                        x = queue.take();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.err.println("Receive: " + x);
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

}
